package cn.bx.bid.service;

import cn.bx.bid.entity.User;
import cn.bx.bid.repository.UserRepository;
import cn.bx.bid.util.Md5Util;
import cn.bx.bid.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional(readOnly = false)
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User get(long id) {
        Optional<User> findById = userRepository.findById(id);
        return findById.get();
    }

    //不返回int,返回对象
    public int save(User user) {
        userRepository.save(user);
        return 1;
    }

    public int delBy(long id) {
        userRepository.deleteById(id);
        return 1;
    }

    public int update(User user) {
        userRepository.saveAndFlush(user);
        return 1;
    }

    public List<User> search(String name) {
        return userRepository.findByNameContaining(name);
    }

    public Page paging(int pageNo, int pageSize, String name, Date start, Date end) {
        Sort sort = Sort.by(Sort.Order.desc("id"));
        //hibernateg QL:hql
        //sql语法不完全一样
        //PageRequest p=PageRequest.of(page,pageSize);
        PageRequest p = PageRequest.of(pageNo, pageSize, sort);
        //已经考虑了分页的条件,总数...
        //缺点:没有其他条件
        //内部类
        return userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> pList = new ArrayList<>();
                if (StringUtil.isBlank(name) == false)
                    pList.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
                if (start != null) {  //>=
                    //criteriaBuilder.ge
                    Predicate condition = criteriaBuilder.greaterThanOrEqualTo(root.get("enterdate"), start);

                    pList.add(condition);
                }
                if (end != null)//<=
                    pList.add(criteriaBuilder.lessThanOrEqualTo(root.get("enterdate"), end));

                criteriaQuery.where(pList.toArray(new Predicate[0]));
                return criteriaQuery.getRestriction();

            }
        }, p);
    }
    //Page search(String name,Date start,Date end);

    //public List<User> findAllBy(){
    // return userRepository.findAllBy();
    //}

    //select * from user where telephone=? and id!=?
    //验证登录名是否重复
    public boolean checkUserNameRepeat(Long id, String username) {
        User u1 = userRepository.findByUsername(username);
        if (u1 == null) {
            return false;//没有重复
        }
        if (id != null && u1.getId() == id) {
            return false;
        }
        return true;
    }

    //password 要md5一下,然后再比较
    //select * from user where username=? and password=md5(?)
    public User login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            return null;
        }
        return user.getPassword().equals(Md5Util.getMD5(password)) ? user : null;
    }

    public int batchDel(long[] ids) {
        for (long id : ids) {
            User u = new User();
            u.setId(id);
            this.userRepository.delete(u);//对象
        }
        return ids.length;
    }

    public int updatePass(User user) {
        User user1 = userRepository.findById(user.getId()).get();
        user1.setPassword(Md5Util.getMD5(user.getPassword()));
        userRepository.saveAndFlush(user1);
        return 1;
    }

    //重置密码
    /*public int resetPass(long id,String newPass){
        return userRepository.resetPass(id,newPass);
    }*/

}
